let _Vue = null
export default class VueRouter{
    static install(Vue){
        if(VueRouter.install.installed){
            return
        }
        VueRouter.install.installed = true
        _Vue = Vue
        // 混入
        _Vue.mixin({
            beforeCreate(){
                if(this.$options.router){
                    _Vue.prototype.$router = this.$options.router
                }
            }
        })
    }
    constructor(options){
        this.options = options
        this.routerMap = {}
        this.data = _Vue.observable({
            current:'/'
        })
        this.init()
    }
    init(){
        this.createRouterMap()
        this.initComponents(_Vue)
        this.initEvent()
    }
    createRouterMap(){
        this.options.routes.forEach(route => {
            this.routerMap[route.path]=route.component
        })
    }
    initComponents(Vue){
        let self = this
        Vue.component('router-link',{
            props:{
                to:String
            },
            render(h){
                return h('a',{
                    attrs:{
                        href:this.to
                    },
                    on:{
                        click:this.eventHandler
                    }
                },[
                    this.$slots.default
                ])
            },
            methods:{
                eventHandler(e){
                    location.hash = this.to
                    e.preventDefault()
                }
            }
        })
        Vue.component('router-view',{
            render(h){
                const component = self.routerMap[self.data.current]
                return h(component)
            }
        })
    }
    initEvent(){
        window.addEventListener('hashchange',()=>{
            this.data.current = location.hash.slice(1)
        })
    }
}